'use strict';

const Service = require('egg').Service;

class BookService extends Service {
    async page(query) {
        const { ctx, app } = this
        const { Op } = app.Sequelize
        const { page, limit } = query
        const where = { upt_act: { [Op.ne]: 'D' } };
        if (query.book_num) {
            where.book_num = { [Op.like]: `%${query.book_num}%` };
        }
        if (query.book_name) {
            where.book_name = { [Op.like]: `%${query.book_name}%` };
        }
        if (query.username) {
            where.username = { [Op.like]: `%${query.username}%` };
        }
        //还有一个时间
        let revertTime = ctx.helper.formatTime(query.revert_time).split(' ')[0]
        if(query.revert_time) {
            where.revert_time = app.Sequelize.where(app.Sequelize.fn('date', app.Sequelize.col('revert_time')), revertTime)
        }

        const { username } = ctx.state.user
        const { userid } = ctx.state.user;
        const user = await ctx.model.Sys.User.findOne({
            include: {
                model: ctx.model.Sys.Role,
                attributes: ['name']
            },
            where: { id: userid },
            attributes: ['id', 'username']
        });
        const name = user.dataValues.sys_roles[0].dataValues.name
        if (name != '超级管理员') {
            where.username = username
        }

        return await ctx.model.Message.findAndCountAll({
            where,
            offset: (page - 1) * limit,
            limit: parseInt(limit),
            order: [['created_at', 'desc']],
        })
    }
    async create(body) {
        const { ctx, app } = this
        // console.log(body);
        const { Op } = app.Sequelize
        try {
            const res = await ctx.model.Message.findAll({
                where: {
                    username: body.username,
                    book_num: body.book_num,
                    upt_act: { [Op.ne]: 'D' }
                }
            })
            if (res[0]) {
                return { msg: `您已经提醒了【${body.username}】及时归还【${body.book_name}】！` }
            }
            return await ctx.model.Message.create(body)
        } catch (error) {
            console.log(error);
            return false
        }
    }
}
module.exports = BookService;